<?php
    include_once "classes/User.php";
    session_start();
    include_once "session.php";
    if (!isLoggedIn()) {
        exit();
    }
    include_once("db/db_cse305.php");
    
    
    $res = array();
    $OverwriteUserID =  $_SESSION['User']->UserID;
    $lookup = false;
    if ($_SESSION['User']->UserType == "Representative" || $_SESSION['User']->UserType == "Manager") {
        $lookup = true;
        if (isset($_POST["uid"])) {
            $OverwriteUserID = $_POST["uid"];
            if (!is_numeric($OverwriteUserID)) {
                echo "Invalid User ID";
                exit();
            }
        } else {
            exit();
        }
    }
    
    $query = sprintf("SELECT stocks.StockType AS `s`, SUM(orders.NumShares) AS `c` FROM orders JOIN accounts USING (AccountID) JOIN customer ON (accounts.CustomerUserID = customer.UserID) JOIN stocks ON (stocks.StockSymbol = orders.StockSymbol) WHERE customer.UserID = %d GROUP BY stocks.StockType ORDER BY c DESC LIMIT 5",  $OverwriteUserID);
    $result = mysql_query($query) or die(mysql_error());
    $types = array();
    $any = false;
    while ($row = mysql_fetch_array($result)) {
        $any = true;
        $types[] = $row["s"];
        //print ($row["s"]);
        //array_push($types, $row["s"]);
    }
    
    if (!$any && lookup) {
        echo "Invalid User ID";
        exit();
    }
    //print_r($types);
    
    $query = sprintf("SELECT * FROM stocks WHERE StockType IN ('%s') ORDER BY NumberOfShares DESC LIMIT 5", implode("','", $types));
    $result = mysql_query($query) or die(mysql_error());
    
    while ($row = mysql_fetch_array($result)) {
        $res[] = $row["StockSymbol"];
    }
    
    if (count($res) == 0) {
        $query = "SELECT * FROM stocks ORDER BY NumberOfShares DESC LIMIT 5";
        $result = mysql_query($query) or die(mysql_error());
        while ($row = mysql_fetch_array($result)) {
            $res[] = $row["StockSymbol"];
        }
    }
   
    
    echo json_encode($res);
?>